% test_pilot_.m
% David Rowe Oct 2014
%

% Simulation to test pilot assisted coherent FDM QPSK.  QPSK performs
% about 4dB better than DQPSK on HF fading channels, even half of that
% would be very useful.
  
% reqd to make sure we can repeat tests exactly

rand('state',1); 
randn('state',1);

% main test function 

function sim_out = ber_test(sim_in, modulation)
    Fs = 8000;

    verbose          = sim_in.verbose;
    Ntrials          = sim_in.Ntrials;
    Esvec            = sim_in.Esvec;
    plot_scatter     = sim_in.plot_scatter;
    Rs               = sim_in.Rs;
    hf_sim           = sim_in.hf_sim;
    nhfdelay         = sim_in.hf_delay_ms*Rs/1000;
    hf_mag_only      = sim_in.hf_mag_only;
    framesize        = sim_in.framesize;
    Np               = sim_in.Np;
    Ns               = sim_in.Ns;
    coh              = sim_in.coh;

    bps              = 2;
    Nc = Nsymb       = framesize/bps;      % total number of symbols

    prev_sym_tx      = qpsk_mod([0 0])*ones(1,Nc);
    prev_sym_rx      = qpsk_mod([0 0])*ones(1,Nc);

    % Init HF channel model from stored sample files of spreading signal ----------------------------------

    % convert "spreading" samples from 1kHz carrier at Fs to complex
    % baseband, generated by passing a 1kHz sine wave through PathSim
    % with the ccir-poor model, enabling one path at a time.
    
    Fc = 1000; M = Fs/Rs;
    fspread = fopen("../raw/sine1k_2Hz_spread.raw","rb");
    spread1k = fread(fspread, "int16")/10000;
    fclose(fspread);
    fspread = fopen("../raw/sine1k_2ms_delay_2Hz_spread.raw","rb");
    spread1k_2ms = fread(fspread, "int16")/10000;
    fclose(fspread);

    % down convert to complex baseband
    spreadbb = spread1k.*exp(-j*(2*pi*Fc/Fs)*(1:length(spread1k))');
    spreadbb_2ms = spread1k_2ms.*exp(-j*(2*pi*Fc/Fs)*(1:length(spread1k_2ms))');

    % remove -2000 Hz image
    b = fir1(50, 5/Fs);
    spread = filter(b,1,spreadbb);
    spread_2ms = filter(b,1,spreadbb_2ms);
   
    % discard first 1000 samples as these were near 0, probably as
    % PathSim states were ramping up

    spread    = spread(1000:length(spread));
    spread_2ms = spread_2ms(1000:length(spread_2ms));

    % decimate down to Rs

    spread = spread(1:M:length(spread));
    spread_2ms = spread_2ms(1:M:length(spread_2ms));

    % Determine "gain" of HF channel model, so we can normalise
    % carrier power during HF channel sim to calibrate SNR.  I imagine
    % different implementations of ccir-poor would do this in
    % different ways, leading to different BER results.  Oh Well!

    hf_gain = 1.0/sqrt(var(spread)+var(spread_2ms));

    % Start Simulation ----------------------------------------------------------------

    for ne = 1:length(Esvec)
        EsNodB = Esvec(ne);
        EsNo = 10^(EsNodB/10);
    
        variance = 1/EsNo;
         if verbose > 1
            printf("EsNo (dB): %f EsNo: %f variance: %f\n", EsNodB, EsNo, variance);
        end
        
        Terrs = 0;  Tbits = 0;

        tx_symb_log      = [];
        rx_symb_log      = [];
        errors_log       = [];
        Nerrs_log        = [];

        % simulation starts here-----------------------------------
 
        % generate all tx symbols and simulate on HF channel so we can
        % use future and past samples for phase estimation.  We
        % simulate Ntrials+Np so we have enough samples for looking
        % forward and backwards for phase estimation

        tx_bits = zeros(Ntrials+Np*Ns, framesize);
        tx_symb = zeros(1, Nc);
        s_ch = zeros(Ntrials+Np*Ns, Nc);

        for nn = 1: Ntrials+Np*Ns
            tx_bits(nn,:) = round(rand(1,framesize));                       

            % modulate --------------------------------------------

            for c=1:Nc
              tx_symb(c) = qpsk_mod(tx_bits(nn,(2*(c-1)+1):(2*c)));
              if strcmp(modulation,'dqpsk')
                tx_symb(c) *= prev_sym_tx(c);
                prev_sym_tx(c) = tx_symb(c);
              end
            end
            s_ch(nn,:) = tx_symb;
            tx_symb_log = [tx_symb_log tx_symb];

            if hf_sim
              % separation between carriers.  Note this effectively
              % under samples at Rs, I dont think this matters.
              % Equivalent to doing freq shift at Fs, then
              % decimating to Rs.

              wsep = 2*pi*(1+0.5);  % e.g. 75Hz spacing at Rs=50Hz, alpha=0.5 filters

              for c=1:Nc
                hf_model(nn,c) = hf_gain*(spread(nn) + exp(-j*c*wsep*nhfdelay)*spread_2ms(nn));
                %hf_model(nn,c) = 1;
                if hf_mag_only
                  s_ch(nn,c) *= abs(hf_model(nn,c));
                else
                  s_ch(nn,c) *= hf_model(nn,c);
                end
              end
            end         
         end

         % add channel noise
                    
         noise = sqrt(variance*0.5)*(randn(Ntrials+Np*Ns,Nc) + j*randn(Ntrials+Np*Ns,Nc));
         s_ch += noise;
         if hf_sim
           hf_model_noise = hf_model + noise;
         end

         % phase estimation and demodulation

         phi_ = zeros(Ntrials+Np*Ns, Nc);

         for nn = floor(Np*Ns/2)+1:floor(Np*Ns/2)+Ntrials
           
           % pilot assisted phase estimation 

           if coh 
             for c=1:Nc
               k = 1;
               for i = -floor(Np*Ns/2):Ns:floor(Np*Ns/2)
                 % ignore centre sample as that is the current symbol
                 if i != 0
                   phase_samples(k) = hf_model_noise(nn+i,c);
                   %printf("i: %d symb phase: %f\n", i, angle(phase_samples(k)));
                   k++;                     
                 end
               end    
               phi_(nn,c) = angle(sum(phase_samples));
               %printf("phi: %f phi_: %f\n", angle(hf_model(nn,c)), phi_(nn,c));
               s_ch(nn,c) *= exp(-j*phi_(nn,c));
             end
           end
          
           % de-modulate

           rx_bits = zeros(1, framesize);
           for c=1:Nc
             rx_symb(c) = s_ch(nn,c);
             if strcmp(modulation,'dqpsk')
               tmp = rx_symb(c);
               rx_symb(c) *= conj(prev_sym_rx(c)/abs(prev_sym_rx(c)));
               prev_sym_rx(c) = tmp;
             end
             rx_bits((2*(c-1)+1):(2*c)) = qpsk_demod(rx_symb(c));
             rx_symb_log = [rx_symb_log rx_symb(c)];
           end
            
           % Measure BER

           error_positions = xor(rx_bits, tx_bits(nn,:));
           Nerrs = sum(error_positions);
           Terrs += Nerrs;
           Tbits += framesize;
           errors_log = [errors_log error_positions];
           Nerrs_log = [Nerrs_log Nerrs];
        end
    
        TERvec(ne) = Terrs;
        BERvec(ne) = Terrs/Tbits;

        if verbose 
            av_tx_pwr = (tx_symb_log * tx_symb_log')/length(tx_symb_log);

            printf("EsNo (dB): %3.1f  Terrs: %d BER %4.3f QPSK BER theory %4.3f av_tx_pwr: %3.2f", EsNodB, Terrs,
                   Terrs/Tbits, 0.5*erfc(sqrt(EsNo/2)), av_tx_pwr);
            printf("\n");
        end
    end
    
    Ebvec = Esvec - 10*log10(bps);
    sim_out.BERvec          = BERvec;
    sim_out.Ebvec           = Ebvec;
    sim_out.TERvec          = TERvec;
    sim_out.errors_log      = errors_log;

    if plot_scatter
        figure(2);
        clf;
        scat = rx_symb_log .* exp(j*pi/4);
        plot(real(scat), imag(scat),'+');
        title('Scatter plot');

        if hf_sim
          figure(3);
          clf;
        
          y = 1:Ntrials+floor(Np/2);
          x = 1:Nc;
          EsNodBSurface = 20*log10(abs(hf_model(y,:))) - 10*log10(variance);
          EsNodBSurface(find(EsNodBSurface < -5)) = -5;
          mesh(x,y,EsNodBSurface);
          grid
          axis([1 Nc 1 Rs*5 -5 15])
          title('HF Channel Es/No');

          if verbose 
            [m n] = size(hf_model);
            av_hf_pwr = sum(sum(abs(hf_model(:,:)).^2))/(m*n);
            printf("average HF power: %3.2f over %d symbols\n", av_hf_pwr, m*n);
          end

          figure(5);
          clf
          subplot(211)
          [m n] = size(hf_model);
          plot(angle(hf_model(1:m,1)),'g;HF channel phase;')
          hold on;
          plot(phi_(1:m,1),'r+;Estimated HF channel phase;')
          ylabel('Phase (rads)');
          subplot(212)
          plot(abs(hf_model(1:m,1)))
          ylabel('Amplitude');
          xlabel('Time (symbols)');
        end

        figure(4)
        clf
        stem(Nerrs_log)

   end

endfunction

% Gray coded QPSK modulation function

function symbol = qpsk_mod(two_bits)
    two_bits_decimal = sum(two_bits .* [2 1]); 
    switch(two_bits_decimal)
        case (0) symbol =  1;
        case (1) symbol =  j;
        case (2) symbol = -j;
        case (3) symbol = -1;
    endswitch
endfunction

% Gray coded QPSK demodulation function

function two_bits = qpsk_demod(symbol)
    if isscalar(symbol) == 0
        printf("only works with scalars\n");
        return;
    end
    bit0 = real(symbol*exp(j*pi/4)) < 0;
    bit1 = imag(symbol*exp(j*pi/4)) < 0;
    two_bits = [bit1 bit0];
endfunction


function sim_in = standard_init
  sim_in.verbose          = 1;
  sim_in.plot_scatter     = 0;

  sim_in.Esvec            = 5; 
  sim_in.Ntrials          = 30;
  sim_in.Rs               = 50;
  sim_in.framesize        = 8;
  sim_in.ml               = 0;

  sim_in.hf_delay_ms      = 2;
  sim_in.hf_sim           = 0;
  sim_in.hf_mag_only      = 0;
endfunction


function test_curves

  sim_in = standard_init();

  sim_in.Ntrials          = 2000;

  sim_in.hf_sim           = 0;
  sim_in.plot_scatter     = 0;
  sim_in.Esvec            = 5:15; 
  Ebvec = sim_in.Esvec - 10*log10(2);
  BER_theory = 0.5*erfc(sqrt(10.^(Ebvec/10)));

  sim_in.coh               = 0;
  sim_in.Np                = 2;
  sim_in.Ns                = 8;
  sim_in.Rs                = 100;

  sim_dqpsk                = ber_test(sim_in, 'dqpsk');
  sim_in.hf_sim            = 1;
  sim_dqpsk_hf             = ber_test(sim_in, 'dqpsk');

  sim_in.hf_mag_only       = 1;
  sim_qpsk_hf_ideal        = ber_test(sim_in, 'qpsk');
  sim_in.hf_mag_only       = 0;
  sim_in.coh               = 1;
  sim_in.Np                = 2;
  sim_in.Ns                = 4;
  sim_in.Rs                = 100;
  sim_qpsk_hf_coh1         = ber_test(sim_in, 'qpsk');
  sim_in.Np                = 4;
  sim_in.Ns                = 4;
  sim_in.Rs                = 200;
  sim_qpsk_hf_coh2         = ber_test(sim_in, 'qpsk');
  sim_in.Np                = 4;
  sim_in.Ns                = 8;
  sim_in.Rs                = 200;
  sim_qpsk_hf_coh3         = ber_test(sim_in, 'qpsk');

  figure(1); 
  clf;
  semilogy(Ebvec, BER_theory,'r;QPSK theory;')
  hold on;
  semilogy(sim_dqpsk.Ebvec, sim_dqpsk.BERvec,'k;DQPSK AWGN;')
  semilogy(sim_dqpsk_hf.Ebvec, sim_dqpsk_hf.BERvec,'k;DQPSK HF;')
  semilogy(sim_qpsk_hf_ideal.Ebvec, sim_qpsk_hf_ideal.BERvec,'c;QPSK HF ideal;')
  semilogy(sim_qpsk_hf_coh1.Ebvec, sim_qpsk_hf_coh1.BERvec,'g;QPSK HF Rs=100 Np=2 Ns=4;')
  semilogy(sim_qpsk_hf_coh2.Ebvec, sim_qpsk_hf_coh2.BERvec,'r;QPSK HF Rs=200 Np=4 Ns=4;')
  semilogy(sim_qpsk_hf_coh3.Ebvec, sim_qpsk_hf_coh3.BERvec,'b;QPSK HF Rs=200 Np=4 Ns=8;')
  hold off;

  xlabel('Eb/N0')
  ylabel('BER')
  grid("minor")
  axis([min(Ebvec) max(Ebvec) 1E-3 1])
endfunction


function test_single
  sim_in = standard_init();

  sim_in.verbose          = 1;
  sim_in.plot_scatter     = 1;
  sim_in.Ntrials          = 1000;

  sim_in.hf_mag_only      = 0;
  sim_in.hf_sim           = 1;
  sim_in.Esvec            = 10;
  sim_in.coh              = 1;
  sim_in.Rs               = 100;
  sim_in.Np               = 2;
  sim_in.Ns               = 1;

  sim_qpsk_hf             = ber_test(sim_in, 'qpsk');
endfunction


% Start simulations ---------------------------------------

more off;

test_curves();
%test_single();
